<?php
/**
 * Created by PhpStorm.
 * User: lance
 * Date: 2017/10/31
 * Time: 15:42
 */

namespace app\manager\admin;

use app\admin\controller\Admin;
use app\admin\controller\Config;
use app\common\builder\ZBuilder;
use app\common\log\distributeRole\DistributeCustomer;
use app\manager\validate\EventLog;
use app\manager\validate\Manager;
use php_identify\libs\AccountIdentify;
use php_identify\libs\DepartmentIdentify;
use php_identify\libs\EmailIdentify;
use php_identify\libs\IdCardIdentify;
use php_identify\libs\Identify;
use php_identify\libs\NameIdentify;
use php_identify\libs\NumberIdentify;
use php_identify\libs\SexIdentify;
use php_excel\libs\Excel;
use think\Db;
use app\common\log\addRole\ManagerAdd;

class Index extends Admin
{
    private $a_data;

    public function managerList()
    {

        $a_where = $this->getMap();
        foreach ($a_where as $s_key => $a_val):
            $s_pre = substr($s_key, 0, strpos($s_key, '.'));
            switch ($s_pre):
                //过滤查找的时候会自动添加表前缀，真正查找时又不添加前缀
                case 'manager':
                    $a_where['xcmanager' . substr($s_key, strpos($s_key, '.'))] = $a_val;
                    unset($a_where[$s_key]);
                    break;
            endswitch;
        endforeach;
        $a_dataList = Db::name('manager')->where($a_where)->order('id desc')->paginate();
        $s_tips = <<<EOT
1.可点击操作栏对应的按钮进行客户经理资料编辑和分配客户的操作。
<br>
2.分配客户后可在日志管理中，客户分配日志中查看详细信息。
EOT;

        return ZBuilder::make('table')
            ->hideCheckbox()
            ->addFilter([
                'name' => 'manager',
                'number' => 'manager',
                'department' => 'manager'
            ])
            ->setSearch([
                'department' => '部门',
                'name' => '姓名',
                'number' => '柜员号',
            ])
            ->setPageTips($s_tips)
            ->addColumns(config('manager_list'))
            ->setRowList($a_dataList)
            ->addRightButton('edit')
            ->addRightButtons([
                //分配客户
                'custom' => [
                    'title' => '分配客户',
                    'icon' => 'fa fa-fw fa-arrow-left',
                    'href' => url('disCustomer', ['id' => '__id__']),

                ],
            ])
            ->addRightButton('custom',
                [
                    'title' => '发送消息',
                    'icon' => 'fa fa-fw fa-comment',
                    'href' => url('sendMsg', ['id' => '__id__']),
                ], true)
            ->fetch();
    }

    /**
     * 编辑
     */
    public function edit($id = '')
    {
        if (request()->isAjax()):
            $o_validate = new Manager();
            $this->a_data = input('');
            if ($o_validate->scene('update')->check($this->a_data) === false):
                $this->error($o_validate->getError());
            endif;
            $o_model = new \app\manager\model\Manager();
            if ($o_model->isUpdate()->save($this->a_data) === false):
                $o_log = new ManagerAdd([
                    'role_id' => $id,
                    'status' => 0,
                    'update' => true,
                    'error' => '更新失败',
                    'role_type' => 2,
                    'content' => json_encode($this->a_data)
                ]);
                $o_log->addOne();
                $this->error('更新失败！');
            else:
                //记录成功日志
                $o_log = new ManagerAdd([
                    'role_id' => $id,
                    'status' => 1,
                    'update' => true,
                    'error' => '',
                    'role_type' => 2,
                    'content' => json_encode($this->a_data)
                ]);
                $o_log->addOne();
                $this->success('更新成功！');

            endif;
        endif;
        $a_items = \config('manager_info');
        $a_items[3][0] = 'static';
        $a_items[3][3] = '不可修改';
        return ZBuilder::make('form')
            ->addHidden('id', $id)
            ->addFormItems($a_items)
            ->setFormData(Db::name('manager')->where('id', $id)->find())
            ->fetch();
    }

    /**
     * 为客户经理分配客户
     */
    public function disCustomer()
    {
        if (request()->isAjax()):
            $a_ids = input('post.ids/a');
            $a_ids = array_map('intval', $a_ids);
            $i_managerId = input('mid/d', 0);
            //分配客户
            $i_count = count($a_ids);//总的客户数目
            $i_sucNum = 0;//成功分配人数
            $i_failNum = 0;//失败分配人数
            $s_message = '';
            switch (ROLE_ID):
                case 1:
                    $s_message = '管理员分配客户';
                    break;
                case 2:
                    $s_message = '领导分配客户';
                    break;
            endswitch;
            foreach ($a_ids as $i_id):
                $o_dis = new DistributeCustomer([
                    'customer_id' => $i_id,
                    'manager_id' => $i_managerId,
                    'message' => $s_message
                ]);
                $m_rsl = $o_dis->disOne();
                if ($m_rsl !== true):
                    $i_failNum++;
                else:
                    $i_sucNum++;
                endif;
            endforeach;
            $this->success("此次分配客户" . $i_count . '人,成功' . $i_sucNum . ',失败' . $i_failNum . '人。具体可看客户分配日志');
        else:

            $a_manager = Db::name('manager')->where('id', input('id/d', 0))->find();
            $s_department = $a_manager['department'];//部门名
            $s_name = $a_manager['name'];//客户经理姓名
            $s_number = $a_manager['number'];//柜员号
            $s_tips = <<<EOT
正在为<b style="color:red">{$s_department}</b></b>部门客户经理<b style="color:red">{$s_name}({$s_number})</b>分配客户。
EOT;

            //确认分配按钮
            $a_yes = [
                'title' => '确认分配',
                'icon' => 'fa fa-fw fa-check',
                'class' => 'btn btn-danger ajax-post confirm',
                'href' => url('disCustomer', ['mid' => input('id/d', 0)]),
                'data-title' => '确定分配？',
                'data-tips' => '分配后具体可在日志管理中查看客户分配日志'
            ];
            $a_customer = Db::name('customer')->where('manager_id', 0)->paginate();
            return ZBuilder::make('table')
                ->setPageTips($s_tips)
                ->addColumns(config('customer_list'))
                ->setRowList($a_customer)
                ->addTopButton('custom', $a_yes)
                ->fetch();
        endif;
    }

    /**
     * 向客户经理发送消息
     */
    function sendMsg()
    {
        if (request()->isAjax()):
            //验证消息内容
            $o_validate = new EventLog();
            if ($o_validate->check(input('')) === false):
                $this->error($o_validate->getError());
            endif;
            //添加消息
            $a_insertData = input('');
            unset($a_insertData['id']);
            $a_insertData = array_merge(['time' => $_SERVER['REQUEST_TIME']], $a_insertData);
            if (!Db::name('event_log')->insert($a_insertData)):
                $this->error("发送失败！");
            else:
                $this->success("发送成功！");
            endif;
        else:
            return ZBuilder::make('form')
                ->addHidden('send_id', UID)
                ->addHidden('manager_id', input('id'))
                ->addFormItems(config('send_msg'))
                ->fetch();
        endif;
    }

    /**
     * 创建客户经理资料
     */
    public function createManagers()
    {
        set_time_limit(0);
        $a_data = [];
        $i_nums = 10;
        $i_sign = 1;
        $o_manager = new Identify();
        $o_department = new DepartmentIdentify('部门');
        $o_name = new NameIdentify("姓名");
        $o_account = new AccountIdentify('柜员号');
        $o_idCard = new IdCardIdentify('身份证');
        $o_sex = new SexIdentify('性别');
        $o_number1 = new NumberIdentify('移动电话');
        $o_email = new EmailIdentify('电子邮件');
        $o_number2 = new NumberIdentify("办公电话");
        while ($i_sign <= $i_nums):
            $o_department->decorate($o_manager);
            $o_name->decorate($o_department);
            $o_account->decorate($o_name);
            $o_idCard->decorate($o_account);
            $o_sex->decorate($o_idCard);
            $o_number1->decorate($o_sex);
            $o_number2->decorate($o_number1);
            $o_email->decorate($o_number2);
            $a_tmp = [];
            $o_email->get($a_tmp);
            $a_data[] = $a_tmp;
            $i_sign++;
        endwhile;
        $a_data = array_map(function ($a_item) {
            return array_values($a_item);
        }, $a_data);
        $o_excel = new Excel();
        $a_manager = config('manager_info');
        array_shift($a_manager);
        $s_tail = ord('A') + count($a_data[0]) - 1;
        $a_fields = array_map(function ($a_item) {
            return $a_item[2];
        }, $a_manager);
        $o_excel->export(
            range('A', chr($s_tail)),
            $a_fields,
            $a_data, '客户经理测试资料' . uniqid()
        );
        exit;
    }

}